<?php

namespace App\Game\Logic;

use App\Game\Core\AStrategy;
use App\Game\Core\Djs;
use App\Game\Core\Message;
use App\Game\Conf\SubCmd;
use App\Game\Core\Robot;
use App\Game\Core\Room;
use App\Model\User;
use App\Service\Lock;

/**
 *  大奖赛入口
 */
class GrandMatch extends AStrategy
{
    public function exec()
    {
        $account = $this->_params['data']['account'];
        //防止重复操作
        if (!Lock::lock($account . '_grand_math', 3)) {
            return;
        }
        $res = Djs::checkScore($account);
        if (!$res) {
            $msg = ['account' => $account, 'room_no' => null, 'status' => '积分不足', 'info' => '积分不足'];
            Message::pushDataToUser($account, $msg, SubCmd::GAME_QUICK_RESP, 0);
            return;
        }
        ddTitle(1);
        //查询用户是否已经超过挑战次数，每日最多3次
        $playerInfo = Djs::getDjsPlayerData($account);
        $stage = 1;
        if (!empty($playerInfo)) {
            $left_time = $playerInfo['end_time'] - time();
            if ($left_time <= 0 && $playerInfo['turn'] >= 3) {
                Message::pushDataToUser($account, ['status' => '当日最多挑战3次'], SubCmd::GAME_QUICK_RESP, 0);
                return;
            }
            if (!$playerInfo['status'] && $playerInfo['turn'] >= 3) {
                Message::pushDataToUser($account, ['status' => '当日最多挑战3次'], SubCmd::GAME_QUICK_RESP, 0);
                return;
            }
            if (!$playerInfo['status'] && $playerInfo['alive'] > 3) {
                Message::pushDataToUser($account, ['status' => '复活次数不能超过3次'], SubCmd::GAME_QUICK_RESP, 0);
                return;
            }
            if ($playerInfo['stage'] >= 10 && !$playerInfo['get_coupons'] && ($left_time > 0)) {
                Message::pushDataToUser($account, ['status' => '请先领取奖励再开始'], SubCmd::GAME_QUICK_RESP, 0);
                return;
            }
            //重置部分数据
            $timeArr = Djs::generateDjsTime();
            $alive = 0;
            $start_time = $timeArr['start'];
            $end_time = $timeArr['end'];
            $turn = $playerInfo['turn'];
            $get_coupons = 0;
            //连胜情况下，部分数据不重置
            if (($playerInfo['progress'] == Djs::$progress_game_over) &&
                ($playerInfo['end_time'] > time()) &&
                $playerInfo['status'] && $playerInfo['stage']
                < 9 && !$playerInfo['get_coupons']) {
                ddTitle(1.5);
                dd('playerInfo', $playerInfo);
                $stage = $playerInfo['stage'] + 1;
                $alive = $playerInfo['alive'];
                $turn = $playerInfo['turn'];
                $start_time = $playerInfo['start_time'];
                $end_time = $playerInfo['end_time'];
                $get_coupons = $playerInfo['get_coupons'];
            }
            if ($playerInfo['status'] == 0 || $playerInfo['get_coupons'] == 1 || $left_time <= 0) {
                $turn += 1;
                $alive = 0;
            }
            //组装最新的数据
            $playerInfo['status'] = 1;
            $playerInfo['stage'] = $stage;
            $playerInfo['turn'] = $turn;
            $playerInfo['start_time'] = $start_time;
            $playerInfo['end_time'] = $end_time;
            $playerInfo['alive'] = $alive;
            $playerInfo['get_coupons'] = $get_coupons;
            $playerInfo['progress'] = Djs::$progress_game_match;
            //更新用户大奖赛信息
            Djs::updatePlayerData($account, $playerInfo);
            ddTitle(2);
        } else {
            ddTitle(3);
            //初始化玩家大奖赛信息
            $playerInfo = Djs::generatePlayerData($account);
        }
        $msg = [
            'is_real' => 1,
            'player' => User::userInfo($account),
            'status' => 'success',
            'chair_id' => 1,
            'stage' => $playerInfo['stage'],
            'start_time' => $playerInfo['start_time']
        ];

        ddTitle(4);
        if ($msg['stage'] > 9) {
            $msg['stage'] = 9;
        }
        //前四局都是机器人对局
        if ($stage < 5) {
            ddTitle(5);
            $room_no = Djs::createRobotGame($account);
            $msg['room_no'] = $room_no;
            Message::pushDataToUser($account, $msg, SubCmd::GAME_QUICK_RESP);
            sleep(2);
            Robot::addSingleDjsRobot($room_no);
            return;
        }
        ddTitle(6);
        //获取待匹配队列
        $room_no = Djs::getWaitRoom();
        if (!$room_no) {//没有待匹配队列，则创建待匹配队列
            ddTitle(7);
            $room_no = Djs::createWaitRoom($account);
            $msg['room_no'] = $room_no;
            Message::pushDataToUser($account, $msg, SubCmd::GAME_QUICK_RESP);
            return;
        }
        ddTitle(8);
        while (true) {
            if (!Lock::lock('join_grand_match_' . $room_no, 2)) {
                sleep(1);
                continue;
            }
            $waiters = Room::getRoomWait($room_no);
            dd('djs join game waiters', $waiters);
            //未满员则继续等待
            if (count($waiters) < 4) {
                ddTitle(9);
                $chair_id = Djs::joinWaitRoom($room_no, $account);
                $msg = [
                    'status' => 'success',
                    'room_no' => $room_no,
                    'is_real' => 1,
                    'player' => User::userInfo($account),
                    'status' => 'success',
                    'chair_id' => $chair_id,
                    'stage' => $playerInfo['stage'],
                    'start_time' => $playerInfo['start_time']
                ];
                Message::pushDataToUser($account, $msg, SubCmd::GAME_QUICK_RESP);
                $waiters = Room::getRoomWait($room_no);
//                if (count($waiters) < 4) {
//                    sleep(2);
//                    Robot::addSingleDjsRobot($room_no);
//                }
                if (count($waiters) == 4) {
                    sleep(1);
                    ddTitle(9);
                    //满员
                    $players = Djs::initMatchData($room_no);
                    $msg = [
                        'status' => 'success',
                        'room_no' => $room_no,
                        'players' => $players
                    ];
                    Message::broadcast($room_no, $msg, SubCmd::GAME_QUICK_MATCH, 1);
                    Djs::removeWaitRoom($room_no);
                }

                break;
            }

        }
    }


}